package com.example.config;

import com.example.entity.SysUser;
import com.example.entity.vo.UsrRole;
import com.example.service.ISysUserService;
import com.example.ulit.JwtUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

//@Component
@Service
public class MyUserDetailsservice implements UserDetailsService {


    @Resource
    ISysUserService sysUserService;


    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UsrRole usrRole = sysUserService.searchAllByUsrName(userName);
        if(usrRole != null){
            List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_" + usrRole.getRoleName());
            return new User(usrRole.getUsrName(),new BCryptPasswordEncoder().encode(usrRole.getUsrPassword()),authorityList);
        }else {
            return null;
        }
    }
}
